<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="第七章：系统框架(1)第47条：熟悉系统框架FoundationFoundation 框架中的类，使用 NS 这个前缀，此前缀是在 Objective-C 语言用作 NeXTSTEP 操作系统的编程语言时首度确定的。Foundation 框架是 Objective-C 应用程序的基础。Foundation 框架不仅提供了 collection 等基础核心功能，而且还提供了字符串处理这样的复杂功能。">
<meta property="og:type" content="article">
<meta property="og:title" content="《Effective Objective-C 2.0》第七章阅读笔记(1)">
<meta property="og:url" content="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%83%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="第七章：系统框架(1)第47条：熟悉系统框架FoundationFoundation 框架中的类，使用 NS 这个前缀，此前缀是在 Objective-C 语言用作 NeXTSTEP 操作系统的编程语言时首度确定的。Foundation 框架是 Objective-C 应用程序的基础。Foundation 框架不仅提供了 collection 等基础核心功能，而且还提供了字符串处理这样的复杂功能。">
<meta property="og:locale">
<meta property="article:published_time" content="2018-05-27T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-01T08:21:36.632Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Effective Objective-C 2.0">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%83%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%83%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/","path":"2018/05/2018/05/《Effective Objective-C 2.0》第七章阅读笔记(1)/","title":"《Effective Objective-C 2.0》第七章阅读笔记(1)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>《Effective Objective-C 2.0》第七章阅读笔记(1) | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC%E4%B8%83%E7%AB%A0%EF%BC%9A%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6-1"><span class="nav-number">1.</span> <span class="nav-text">第七章：系统框架(1)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC47%E6%9D%A1%EF%BC%9A%E7%86%9F%E6%82%89%E7%B3%BB%E7%BB%9F%E6%A1%86%E6%9E%B6"><span class="nav-number">1.1.</span> <span class="nav-text">第47条：熟悉系统框架</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Foundation"><span class="nav-number">1.1.0.1.</span> <span class="nav-text">Foundation</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreFoundation"><span class="nav-number">1.1.0.2.</span> <span class="nav-text">CoreFoundation</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CFNetWork"><span class="nav-number">1.1.0.3.</span> <span class="nav-text">CFNetWork</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreAudio"><span class="nav-number">1.1.0.4.</span> <span class="nav-text">CoreAudio</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#AVFoundation"><span class="nav-number">1.1.0.5.</span> <span class="nav-text">AVFoundation</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreData"><span class="nav-number">1.1.0.6.</span> <span class="nav-text">CoreData</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreText"><span class="nav-number">1.1.0.7.</span> <span class="nav-text">CoreText</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#UIKit"><span class="nav-number">1.1.0.8.</span> <span class="nav-text">UIKit</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreAnimation"><span class="nav-number">1.1.0.9.</span> <span class="nav-text">CoreAnimation</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CoreGraphics"><span class="nav-number">1.1.0.10.</span> <span class="nav-text">CoreGraphics</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">1.1.1.</span> <span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC48%E6%9D%A1%EF%BC%9A%E5%A4%9A%E7%94%A8%E5%9D%97%E6%9E%9A%E4%B8%BE%EF%BC%8C%E5%B0%91%E7%94%A8-for-%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.2.</span> <span class="nav-text">第48条：多用块枚举，少用 for 循环</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#for-%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.2.1.</span> <span class="nav-text">for 循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BF%AB%E9%80%9F%E9%81%8D%E5%8E%86"><span class="nav-number">1.2.2.</span> <span class="nav-text">快速遍历</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8E%E5%9D%97%E7%9A%84%E9%81%8D%E5%8E%86%E6%96%B9%E5%BC%8F"><span class="nav-number">1.2.3.</span> <span class="nav-text">基于块的遍历方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%AC%AC49%E6%9D%A1%EF%BC%9A%E5%AF%B9%E8%87%AA%E5%AE%9A%E4%B9%89%E5%85%B6%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E8%AF%AD%E4%B9%89%E7%9A%84-collection-%E4%BD%BF%E7%94%A8%E6%97%A0%E7%BC%9D%E6%A1%A5%E6%8E%A5"><span class="nav-number">1.3.</span> <span class="nav-text">第49条：对自定义其内存管理语义的 collection 使用无缝桥接</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%83%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="《Effective Objective-C 2.0》第七章阅读笔记(1) | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《Effective Objective-C 2.0》第七章阅读笔记(1)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-05-28 00:00:00" itemprop="dateCreated datePublished" datetime="2018-05-28T00:00:00+08:00">2018-05-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:21:36" itemprop="dateModified" datetime="2018-07-01T16:21:36+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第七章：系统框架-1"><a href="#第七章：系统框架-1" class="headerlink" title="第七章：系统框架(1)"></a><center>第七章：系统框架(1)</center></h1><h2 id="第47条：熟悉系统框架"><a href="#第47条：熟悉系统框架" class="headerlink" title="第47条：熟悉系统框架"></a>第47条：熟悉系统框架</h2><h4 id="Foundation"><a href="#Foundation" class="headerlink" title="Foundation"></a>Foundation</h4><p>Foundation 框架中的类，使用 NS 这个前缀，此前缀是在 Objective-C 语言用作 NeXTSTEP 操作系统的编程语言时首度确定的。Foundation 框架是 Objective-C 应用程序的基础。Foundation 框架不仅提供了 collection 等基础核心功能，而且还提供了字符串处理这样的复杂功能。</p>
<h4 id="CoreFoundation"><a href="#CoreFoundation" class="headerlink" title="CoreFoundation"></a>CoreFoundation</h4><p>CoreFoundation 框架不是 Objective-C 框架，但它却是 Objective-C 应用程序时所应熟悉的重要框架，Foundation 框架中的许多功能，都可以在此框架中找到对应的 C 语言 API。CoreFoundation 与 Foundation 名字相似、联系紧密。能做到“无缝桥接”，可以把 CoreFoundation 框架中的 C 语言数据结构平滑转换为 Foundation 中的 Objective-C 对象，也可以反向转换。比如：NSString 与 CFString 可以互转。</p>
<h4 id="CFNetWork"><a href="#CFNetWork" class="headerlink" title="CFNetWork"></a>CFNetWork</h4><p>此框架提供了 C 语言级别的网络通信能力，它将”BSD套接字”（BSD socket）抽象成易于使用的网络接口。而 Foundation 则将该框架里的部分内容封装为 Objective-C 语言的接口，以便于进行网络通信，例如可以用 NSURLConnection 从 URL 中下载数据。</p>
<h4 id="CoreAudio"><a href="#CoreAudio" class="headerlink" title="CoreAudio"></a>CoreAudio</h4><p>该框架所提供的 C 语言 API 可用来操作设备上的音频硬件。这个框架属于比较难用的那种，因为音频处理本身就很复杂。所幸由这套 API 可以抽象出另外一套 Objective-C 式的 API，用后者来处理音频问题会更简单些。</p>
<h4 id="AVFoundation"><a href="#AVFoundation" class="headerlink" title="AVFoundation"></a>AVFoundation</h4><p>此框架所提供的 Objective-C 对象可用来回放并录制音频及视频，比如能够在 UI 视图类里播放视频。</p>
<h4 id="CoreData"><a href="#CoreData" class="headerlink" title="CoreData"></a>CoreData</h4><p>此框架提供的 Objective-C 接口可以将对象放入数据库，便于持久保存。CoreData 会处理数据的获取及存储事宜，而且可以跨越 Mac OS X 及 iOS 平台。</p>
<h4 id="CoreText"><a href="#CoreText" class="headerlink" title="CoreText"></a>CoreText</h4><p>此框架提供的 C 语言接口可以高效执行文字排版及渲染操作。</p>
<h4 id="UIKit"><a href="#UIKit" class="headerlink" title="UIKit"></a>UIKit</h4><p>我们可能会编写使用 UI 框架的 Mac OS X 或 iOS 应用程序。这两个平台的核心 UI 框架分别叫做 Appkit 及 UIKit，它们都提供了构建在Foundation 与 CoreFoundation 之上的 Objective-C 类。框架里含有 UI 元素，也含有粘合机制，令开发者可将所有相关内容组装为应用程序。</p>
<h4 id="CoreAnimation"><a href="#CoreAnimation" class="headerlink" title="CoreAnimation"></a>CoreAnimation</h4><p>CoreAnimation 是用 Objective-C 语言写成的，它提供了一些工具，而 UI 框架则用这些工具来渲染图形并播放动画。开发者编程时可能从来不会深入到这种级别，不过知道该该框架总是好的。CoreAnimation 本身并不是框架，它是 QuartzCore 框架的一部分。然而在框架的国度里，CoreAnimation 仍应算作“一等公民”(first-class citizen)。</p>
<h4 id="CoreGraphics"><a href="#CoreGraphics" class="headerlink" title="CoreGraphics"></a>CoreGraphics</h4><p>CoreGraphics 框架以 C 语言写成，其中提供了 2D 渲染所必备的数据结构与函数。例如，其中定义了 CGPoint、CGSize、CGRect 等数据结构，而 UIKit 框架中 UIView 类在确定视图控件之间的相对位置时，这些数据结构都要用到。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>系统框架给我们提供了构建应用程序所需的核心功能。<br>Objective-C 编程经常需要使用底层的 C 语言级 API。好处是可以绕过 Objective-C 运行期系统，从而提供执行速度。<br>由于 ARC 只负责 Objective-C 对象，所以使用 C 语言级别的 API 时尤其要注意内存管理问题。</p>
<h2 id="第48条：多用块枚举，少用-for-循环"><a href="#第48条：多用块枚举，少用-for-循环" class="headerlink" title="第48条：多用块枚举，少用 for 循环"></a>第48条：多用块枚举，少用 for 循环</h2><p>在编程中经常需要列举 collection 中的元素，当前的 Objective-C 语言有很多种办法实现此功能，比较常用的有，标准 C 语言循环， Objective-C 2.0 的快速遍历，以及“块”循环。</p>
<h3 id="for-循环"><a href="#for-循环" class="headerlink" title="for 循环"></a>for 循环</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Dictionary</span></span><br><span class="line"><span class="built_in">NSArray</span> *anArray = <span class="comment">/*...*/</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; anArray.count; i++) &#123;</span><br><span class="line">	<span class="type">id</span> object = anArray[i];</span><br><span class="line">	<span class="comment">// Do something with &#x27;object&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSDictionary</span></span><br><span class="line"><span class="built_in">NSDictionary</span> *aDictionary = <span class="comment">/*...*/</span>;</span><br><span class="line"><span class="built_in">NSArray</span> *keys = [aDictionary allKeys];</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; keys.count; i++) &#123;</span><br><span class="line">	<span class="type">id</span> key = keys[i];</span><br><span class="line">	<span class="type">id</span> value = aDictionary[key];</span><br><span class="line">	<span class="comment">// Do something with &#x27;key&#x27; and &#x27;value&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSSet</span></span><br><span class="line"><span class="built_in">NSSet</span> *aSet = <span class="comment">/*...*/</span>;</span><br><span class="line"><span class="built_in">NSArray</span> *objects = [aSet allObjects];</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; objects.count; i++) &#123;</span><br><span class="line">	<span class="type">id</span> object = objects[i];</span><br><span class="line">	<span class="comment">// Do something with &#x27;object&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>for 循环的缺点就是有时需要创建额外的对象才能完成遍历。  </p>
<p>在这里，字典与 set 都是”无序的”（ unordered ），所以无法根据特定的整数下标来直接访问其中的值。于是，就需要先获取字典里的所有键或是 set 里的所有对象，这两种情况下，都可以在获取到的有序数组上遍历，以便借此访问原字典及原 set 中得值。创建这个附加数组会有额外的开销，而且还会多创建一个数组对象，它会保留 collection 中得所有元素对象。</p>
<h3 id="快速遍历"><a href="#快速遍历" class="headerlink" title="快速遍历"></a>快速遍历</h3><p>Objective-C 2.0 引入了快速遍历这一功能。快速遍历语法更简洁，它为 for 循环开设了 in 关键字。这个关键字大幅简化了遍历 collection 所需的语法。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSArray</span></span><br><span class="line"><span class="built_in">NSArray</span> *anArray = <span class="comment">/* ... */</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">id</span> object <span class="keyword">in</span> anArray) &#123;</span><br><span class="line">	<span class="comment">// Do something with &#x27;object&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSDictionary </span></span><br><span class="line"><span class="built_in">NSDictionary</span> *aDictionary = <span class="comment">/* ... */</span>; </span><br><span class="line"><span class="keyword">for</span> (<span class="type">id</span> key <span class="keyword">in</span> aDictionary) &#123; </span><br><span class="line">	<span class="type">id</span> value = aDictionary[key]; </span><br><span class="line">	<span class="comment">// Do something with &#x27;key&#x27; and &#x27;value&#x27; </span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSSet</span></span><br><span class="line"><span class="built_in">NSSet</span> *aSet = <span class="comment">/* ... */</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">id</span> object <span class="keyword">in</span> aSet) &#123;</span><br><span class="line">	<span class="comment">// Do something with &#x27;object&#x27;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这种遍历方式简单且效率高，然而如果在遍历字典时需要同时获取键与值，那么会多出来一步。而且，与传统 for 循环不同，这种遍历方式无法轻松获取当前遍历操作所针对的下标。</p>
<h3 id="基于块的遍历方式"><a href="#基于块的遍历方式" class="headerlink" title="基于块的遍历方式"></a>基于块的遍历方式</h3><p>在当前的 Objective-C 语言中，最新引入的一种做法就是基于块来遍历。NSArray、NSDictionary、NSSet 中定义了下面这个方法，可以实现最基本的遍历功能：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSArray</span></span><br><span class="line">- (<span class="type">void</span>)enumerateObjectsUsingBlock:(<span class="type">void</span>(^)(<span class="type">id</span> object, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> *stop))block;</span><br><span class="line"><span class="comment">// NSDictionary</span></span><br><span class="line">- (<span class="type">void</span>)enumerateKeysAndObjectsUsingBlock:(<span class="type">void</span>(^)(<span class="type">id</span> key, <span class="type">id</span> object, <span class="type">BOOL</span> *stop))block;</span><br><span class="line"><span class="comment">// NSSet</span></span><br><span class="line">- (<span class="type">void</span>)enumerateObjectsUsingBlock:(<span class="type">void</span>(^)(<span class="type">id</span> object, <span class="type">BOOL</span> *stop))block;</span><br></pre></td></tr></table></figure>
<p>NSArray 对应的块有三个参数，分别是当前迭代所针对的对象、所针对的下标，以及指向布尔值的指针。前两个参数的含义不言而喻。而通过第三个参数所提供的机制，开发者可以终止遍历操作。其他两个类似。<br>使用下面代码可以遍历数组   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSArray</span></span><br><span class="line"><span class="built_in">NSArray</span> *anArray = <span class="comment">/* ... */</span>;</span><br><span class="line">[anArray enumerateObjectsUsingBlock:^(<span class="type">id</span> object, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> *stop) &#123;</span><br><span class="line">	<span class="comment">// Do something with &#x27;object&#x27;</span></span><br><span class="line">	<span class="keyword">if</span> (shouldStop) &#123;</span><br><span class="line">		*stop = <span class="literal">YES</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSDictionary</span></span><br><span class="line"><span class="built_in">NSDictionary</span> *aDictionary = <span class="comment">/* ... */</span>;</span><br><span class="line">[aDictionary enumerateKeysAndObjectsUsingBlock:^(<span class="type">id</span> key, <span class="type">id</span> object, <span class="type">BOOL</span> *stop) &#123;</span><br><span class="line">	<span class="comment">// Do something with &#x27;key&#x27; and &#x27;object&#x27;</span></span><br><span class="line">	<span class="keyword">if</span> (shouldStop) &#123;</span><br><span class="line">		*stop = <span class="literal">YES</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSSet</span></span><br><span class="line"><span class="built_in">NSSet</span> *aSet = <span class="comment">/* ... */</span>;</span><br><span class="line">[aSet enumerateObjectsUsingBlock:^(<span class="type">id</span> object, <span class="type">BOOL</span> *stop) &#123;</span><br><span class="line">	<span class="comment">// Do something with &#x27;object&#x27;</span></span><br><span class="line">	<span class="keyword">if</span> (shouldStop) &#123;</span><br><span class="line">		*stop = <span class="literal">YES</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<p>遍历时可以直接从 block 里获取更多信息。在遍历数组时，可以知道当前所针对的下标。遍历有序 NSSet（NSOrderedSet）时也一样。而在遍历字典时，无须额外编码，即可同时获取键与值，因而省去了根据给定键来获取对应值这一步。用这种方式遍历字典，可以同时得知键与值，这很可能比其他方式快很多，因为在字典内部的数据结构中，键与值本来就是存储在一起的。同时，使用这种方法能够修改 block 的方法名，以免进行类型转换的操作，从效果上讲，相当于把本来需要执行的类型转换操作交给block方法签名来做。</p>
<p>用此方式也可以执行反向遍历。数组、字典、set都实现了前述方法的另一个版本，使开发者可向其传入“选项掩码”（option mask）：   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)enumerateObjectsWithOptions:(<span class="built_in">NSEnumerationOptions</span>)options usingBlock:(<span class="type">void</span>(^)(<span class="type">id</span> obj, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> *stop))block; </span><br><span class="line">- (<span class="type">void</span>)enumerateKeysAndObjectsWithOptions:(<span class="built_in">NSEnumerationOptions</span>)options usingBlock: (<span class="type">void</span>(^)(<span class="type">id</span> key, <span class="type">id</span> obj, <span class="type">BOOL</span> *stop))block;</span><br></pre></td></tr></table></figure>
<p>NSEnumerationOptions 类型是个 enum，其各种取值可用“按位或”（bitwise OR）连接，用以表明遍历方式。</p>
<p>总体来看，block 枚举法拥有其他遍历方式都具备的优势，而且还能带来更多好处。与快速遍历法相比，它要多用一些代码，可是却能提供遍历时所针对的下标，在遍历字典时也能同时提供键与值，而且还有选项可以开启并发迭代功能。</p>
<h2 id="第49条：对自定义其内存管理语义的-collection-使用无缝桥接"><a href="#第49条：对自定义其内存管理语义的-collection-使用无缝桥接" class="headerlink" title="第49条：对自定义其内存管理语义的 collection 使用无缝桥接"></a>第49条：对自定义其内存管理语义的 collection 使用无缝桥接</h2><p>使用 “无缝桥接” 技术，可以在定义于 Foundation 框架中的 Objective-C 类和定义于 CoreFoundation 框架中 C 数据结构之间相互转换。   </p>
<p>下面代码演示了简单的无缝桥接：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSArray</span> *anNSArray = @[@<span class="number">1</span>,@<span class="number">2</span>,@<span class="number">3</span>,@<span class="number">4</span>,@<span class="number">5</span>];  </span><br><span class="line"><span class="built_in">CFArrayRef</span> aCFArray = (__bridge <span class="built_in">CFArrayRef</span>)anNSArray;  </span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@&quot;size of array = %li&quot;</span>,<span class="built_in">CFArrayGetCount</span>(aCFArray));  </span><br><span class="line"><span class="comment">// Output：size of array = 5</span></span><br></pre></td></tr></table></figure>
<p>转换操作中的 __bridge 告诉 ARC 如何处理所涉及的 Objective-C 对象。__bridge 本身的意思是：ARC 仍然具备这个 Objective-C 对象的所有权。而 __bridge_retained 则与之相反，意味着 ARC 将交出对象的所有权。若是前面那段代码改用它来实现，那么用完数组之后就要加上CFRelease(aCFArray)以释放其内存。与之相似，反向转换可通过 __bridge_transfer 来实现。那么，为什么需要桥接呢？那是因为Foundation 框架中 Objective-C 类所具备的某些功能，是 CoreFoundation 框架中 C 数据结构所不具备的，反之亦然。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Effective-Objective-C-2-0/" rel="tag"># Effective Objective-C 2.0</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E5%85%AD%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(3)/" rel="prev" title="《Effective Objective-C 2.0》第六章阅读笔记(3)">
                  <i class="fa fa-chevron-left"></i> 《Effective Objective-C 2.0》第六章阅读笔记(3)
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/05/2018/05/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%83%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/" rel="next" title="《Effective Objective-C 2.0》第七章阅读笔记(2)">
                  《Effective Objective-C 2.0》第七章阅读笔记(2) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
